#!/usr/bin/env python
# Make archive posts easier

import argparse
import os
import re

from datetime import datetime

BASE_PATH = os.path.join(
    os.environ['HOME'], '.dotfiles', 'src', 'blog')

CONTENT = '''[[!if test="enabled(calendar)" then="""
To see posts by date, check out the [[archives]]
"""]]
[[!inline pages="page({page_spec}) and !*Discussion"
  archive=yes limit=10 quick=yes trail=no]]
'''

FRONTMATTER = '''[[!meta date="{date}"]]
[[!meta author="Tyler Cipriani"]]
[[!meta copyright="""
Copyright &copy; {year} Tyler Cipriani
"""]]
[[!meta title="{title}"]]
[[!tag computing]]
'''


def make_path(args):
    year, month, day = args['year'], args['month'], args['day']
    times = {
        'year': {
            'dir': os.path.join(BASE_PATH, 'blog', year),
            'pagespec': './{}/*/*/*',
        },
        'month': {
            'dir': os.path.join(BASE_PATH, 'blog', year, month),
            'pagespec': './{}/*/*',
        },
        'day': {
            'dir': os.path.join(BASE_PATH, 'blog', year, month, day),
            'pagespec': './{}/*',
        },
    }

    for pagetime in times.keys():
        data = times[pagetime]

        if not os.path.exists(data['dir']):
            os.makedirs(data['dir'])

        datadir = os.path.dirname(data['dir'])
        database = os.path.basename(data['dir'])
        datapage = os.path.join(datadir, '{}.mdwn'.format(database))

        if os.path.exists(datapage):
            continue

        with open(datapage, 'w') as f:
            f.write(CONTENT.format(
                page_spec=data['pagespec'].format(args[pagetime])))


def make_safe_title(title):
    dashed_title = '-'.join([re.sub(r'[^-\w]', '-', x.lower()) for x in title])
    return '{}.mdwn'.format(dashed_title)


def make_post_path(year, month, day, title, is_brewing=False):
    safe_title = make_safe_title(title)

    if is_brewing:
        post_path = os.path.join(BASE_PATH, 'brewing')
    else:
        post_path = os.path.join(BASE_PATH, 'blog', year, month, day)

    post_path = os.path.join(post_path, safe_title)

    if os.path.exists(post_path):
        raise Exception('Post path exists: %s', post_path)

    return post_path


def make_post(args):
    year, month, day, post_date = (
        args['year'], args['month'], args['day'], args['datetime']
    )

    title = ' '.join(args['title'])

    post_path = make_post_path(
        year, month, day, args['title'], args['brewing'])

    with open(post_path, 'w') as f:
        f.write(FRONTMATTER.format(year=year, date=post_date, title=title))

    print post_path


def parse_args():
    ap = argparse.ArgumentParser()
    ap.add_argument('-y', '--year', help='year of post')
    ap.add_argument('-m', '--month', help='2 digit month')
    ap.add_argument('-d', '--day', help='2 digit day')
    ap.add_argument('--brewing', action='store_true', help='Is a brewing blog')
    ap.add_argument('title', nargs='*', help='Post title')

    args = vars(ap.parse_args())
    now = datetime.utcnow()

    if not (args.get('year') and args.get('month') and args.get('day')):
        args['datetime'] = datetime.isoformat(now)

    if not args.get('year'):
        args['year'] = now.strftime('%Y')

    if not args.get('month'):
        args['month'] = now.strftime('%m')

    if not args.get('day'):
        args['day'] = now.strftime('%d')

    if not args.get('datetime'):
        args['datetime'] = datetime.isoformat(
            datetime(
                int(args['year']),
                int(args['month']),
                int(args['day'])
            )
        )

    return args


def main():
    args = parse_args()

    if not args['brewing']:
        make_path(args)

    make_post(args)


if __name__ == '__main__':
    main()
